<!-- #V2G功能 -->
<template>
  <view :style="objColor">
    <block v-if="backType == 0">
      <navLod txtColor="#FFFFFF" bgColor="#000000" image="https://oos-cn.ctyunapi.cn/front-end/static/static/back1.png"
        title="放电中" :show_bol="false"></navLod>
    </block>
    <block v-if="backType == 2">
      <homeNav title="放电中" image="https://oos-cn.ctyunapi.cn/front-end/static/static/back1.png" txtColor="#FFFFFF"
        :show_bol="false" bgColor="#000000"></homeNav>
    </block>
    <view class="powerCon" :style="'padding-top:' +
      (widnowH <= 568 ? bar_Height + 40 : bar_Height + 45) +
      'px;'
      ">
      <view>
        <view class="power-info-box">
          <view class="text1">{{chargeInfo.stationName || '--'}}{{chargeInfo.gunName ? '-' + chargeInfo.gunName : ''}}</view>
          <view class="text2">订单编号：{{ chargeInfo.busId || '--' }} </view>
          <view class="text3">
            <image class="infoImg1" src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/safe.png"></image>
            两层安全防护中
          </view>
        </view>
        <!-- 动图 -->
        <view class="loading-warp" style="width: 100%; height: 400rpx">
          <l-svga ref="myCanvas" class="SVGACon"></l-svga>
          <view v-if="chargeInfo.terminalType !=2" class="sosCon">{{chargeInfo.soc || 0}}<text class="sosScale">%</text></view>
        </view>

        <view class="power-info-box">
          <view class="text1">{{chargeInfo.plateno ? chargeInfo.plateno + ' | ' : ''}}SOC放电到{{chargeInfo.socThreshold || '-'}}%结束</view>
          <view class="text2">-{{chargeInfo.ivoltage || '-'}}A | {{chargeInfo.voltage || '--'}}V | -{{chargeInfo.realTimePower || '-'}}kw</view>
          <view class="box1">
            <view class="box-item">
              <view class="text4">{{ chargeInfo.soc || '0' }}% </view>
              <view>
                <u-line-progress :showText="false" activeColor="#0FE485" inactive-color="#ececec" :percentage="chargeInfo.soc || 0"></u-line-progress>
              </view>
            </view>
            <!-- <view class="box-item">
              <view class="text4">
                续航{{chargeInfo.rangeOfEndurance || '-'}}km
              </view>
              <view>
                <u-line-progress :showText="false" activeColor="#2979ff" inactive-color="#ececec"
                  :percentage="0"></u-line-progress>
              </view>
            </view> -->
            <view class="box-item">
              <view class="text4">
                {{ !chargeInfo.remainingtime||chargeInfo.remainingtime==0?'计算中':'剩余' + chargeInfo.remainingtimeStr }}
              </view>
              <view>
                <u-line-progress :showText="false" activeColor="#F87D4B" inactive-color="#ececec"
                  :percentage="100"></u-line-progress>
              </view>
            </view>
          </view>
          <view class="box1" style="margin-top: 40rpx">
            <view class="box-item2">
              <view class="text5">-{{ chargeInfo.powerinfo || '-' }}</view>
              <view class="text6">合计放电(度)</view>
            </view>
            <view class="box-item2">
              <view class="text5">{{ chargeInfo.chargingTime || '--' }}</view>
              <view class="text6">V2G放电时长(min)</view>
            </view>
            <view class="box-item2">
              <view class="text5">{{ chargeInfo.cost || '--' }}</view>
              <view class="text6">合计收益(元)</view>
            </view>
          </view>
        </view>
      </view>
      <view class="stop-btn" @click="onStopDisCharge">停止放电</view>
    </view>


    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog type="info" cancelText="返回首页" confirmText="结束放电" title="温馨提示"
        content="平台检测到当前放电车辆的放电数据长时间未更新，您可选择结束当前订单重新启动。如放电正常可忽略，放电数据稍后会同步，可留意账单记录" @confirm="dialogConfirm"
        @close="dialogClose"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import navLod from "../../../components/navLod/navLod";
import homeNav from "../../../components/homeNav/homeNav";
import https_1 from "@/api/https.js";

var times = null;
const newapp = getApp();

export default {
  components: {
    navLod,
    homeNav,
  },

  data() {
    return {
      backType: 0,
      widnowH: uni.getSystemInfoSync().screenHeight,
      bar_Height: uni.getSystemInfoSync().statusBarHeight,
      busId: "",
      pileNo: "",
      gunNo: "",
      stationId: "",

      waitingTime: 300, // 心跳倒数
      chargeInfo: {
        temperature: false,
        soc: '',
        plateno: false,
        powerinfo: '',
        cost: '',
        realTimePower: '',
        chargingTime: ''
      },
      first: true,
    };
  },

  async onLoad(options) {
    console.log('----options---', options);
    this.busId = options.busId || ''
    this.pileNo = options.pileNo || ''
    this.gunNo = options.gunNo || ''
    this.stationId = options.stationId || ''

    if (options.backType) {
      this.backType = options.backType;
    }

    this.$nextTick(() => {
      this.getMove();
    });
  },

  onShow() {
    this.getChargeState()
  },

  onHide () {
    this.clearTimeFun()
  },

  onUnload () {
    this.clearTimeFun()
  },

  methods: {
    // 放电详情
    async getChargeState() {
      return new Promise((resolve, reject) => {
        var that = this
        https_1.querChargeOnline({
          busId: that.busId,
          pileNo: that.pileNo,
          gunNo: that.gunNo,
        }).then(function (res) {
          if (res.code == 0 || res.code == 41623) {
            if (res.data.gunNo) {
              that.waitingTime = 300
              const chargingData = res.data

              that.billId = chargingData.billId
              that.stationId = chargingData.stationId

              if (chargingData.gunState == 3) {
                chargingData.voltage = (chargingData.voltage / 1000).toFixed(3) // 电压
                chargingData.power = (chargingData.power / 1000).toFixed(3) // 电量
                chargingData.cost = (chargingData.cost / 100).toFixed(4) // 费用
                chargingData.ivoltage = (chargingData.ivoltage / 1000).toFixed(3) //电流
                chargingData.powerinfo = (chargingData.powerinfo / 1000).toFixed(3) //已放电量
                chargingData.identCode = chargingData.identCode //停止放电验证码
                chargingData.remainingtimeStr = that.formatMinutesToTime(Number(chargingData.remainingtime))
                that.chargeInfo = chargingData
              } else {
                clearInterval(times)
                if (chargingData.gunState === 1 || chargingData.gunState === 4) {
                  // 空闲 || 放电完成
                  that.showToast(res.msg, '放电完成')
                } else if (chargingData.gunState === 5) {
                  // 离线
                  that.showToast(res.msg, '桩离线')
                } else if (chargingData.gunState === 7) {
                  // 故障
                  that.showToast(res.msg, '故障')
                } else {
                  // 其他
                  that.showModal(res.msg)
                }
              }
              // 第一次
              if (that.first) {
                that.first = false
                times = setInterval(() => {
                  console.log('---循环检测状态---')
                  that.getChargeState()
                }, 10000)
              }
            }

            if (res.code == 41623) {
              that.$refs.alertDialog.open()
              that.billId = res.data.billId
              that.stationId = res.data.stationId
              that.clearTimeFun()
            }
          } else if (res.code == 40624 || res.code == 40623 || res.code == 40613 || res.code == 40600 || res.code == 3) {
            that.clearTimeFun()
            that.billId = res.data ? res.data.billId : 0
            that.stationId = res.data ? res.data.stationId : 0
            uni.showModal({
              title: '停止放电',
              content: '平台检测放电已结束，是否结束当前放电？',
              confirmText: '结束放电',
              showCancel: false,
              confirmColor: that.objColor2.textColor,
              success: function (res) {
                if (res.confirm) {
                  that.stop()
                }
              }
            });
          } else if (res.code == 41623) {
            that.clearTimeFun()
            that.billId = res.data ? res.data.billId : 0
            that.stationId = res.data ? res.data.stationId : 0
            uni.showModal({
              title: '提示',
              content: '平台检测到当前放电车辆的放电数据长时间未更新，您可选择结束当前订单重新启动。如放电正常可忽略，放电数据稍后会同步，可留意账单记录',
              confirmText: '结束放电',
              cancelText: '返回首页',
              confirmColor: that.objColor2.textColor,
              success: function (res) {
                if (res.confirm) {
                  that.stop()
                } else {
                  uni.reLaunch({
                    url: '/pages/index/index'
                  })
                }
              }
            });
          }

          resolve('');
        })
      })
    },

    showToast(str1, str2) {
      uni.showToast({
        title: str1 || str2,
        icon: 'none',
        duration: 2000
      });
    },

    formatMinutesToTime(minutes) {
      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;

      // 使用 padStart 方法确保小时和分钟都是两位数
      const formattedHours = String(hours).padStart(2, '0');
      const formattedMinutes = String(remainingMinutes).padStart(2, '0');

      return `${formattedHours}小时${formattedMinutes}分`;
    },

    dialogConfirm() {
      this.$refs.alertDialog.close()
      this.stop();
    },

    dialogClose() {
      this.$refs.alertDialog.close()
      uni.switchTab({
        url: '/pages/index/index'
      });
    },

    // 获取动图svga
    async getMove() {
      this.$refs.myCanvas.render(async (parser, player) => {
        try {
          //#ifdef APP-PLUS || MP-WEIXIN
          var videoItem = "";
          if (newapp.globalData.sellerNo == "hyc") {
            videoItem = await parser.load(
              `${newapp.globalData.imgUrl}/h5/cartoon/greenBall3.svga`
            );
          } else {
            videoItem = await parser.load(
              "https://oos-cn.ctyunapi.cn/front-end/static/cartoon/greenBall3.svga"
            );
          }
          //#endif
          //#ifdef H5
          var videoItem = await parser.load(
            `${newapp.globalData.imgUrl}/h5/cartoon/greenBall3.svga`
          );
          //#endif
          await player.setVideoItem(videoItem);
          uni.hideLoading();
          // 设置当前动画的循环次数，0代表无限循环 默认 0
          player.loops = 0;
          // 开始播放动画，reverse = true 时则反向播放。
          player.startAnimation();
        } catch (error) {
          console.error('svga播放失败:', error);
        }
      });
    },

    // 停止动画
    stop() {
      var that = this;
      uni.showLoading({
        title: "停止中...",
        mask: true,
      });

      this.$refs.myCanvas.render((parser, player) => {
        player.stopAnimation(true);
        player.clear();
        try {
          player.clearDynamicObjects();
          console.log('---停止动画-success---');
        } catch (err) {
          console.error('结束动画报错：', err);
        }
        uni.redirectTo({
          url: `/homeSub/pages/stopCharging/stopCharging?busId=${this.busId}&billId=${this.billId}&stationId=${this.stationId}&isv2g=1`
        })
      });
    },

    // v2g停止放电
    onStopDisCharge() {
      uni.showModal({
        title: '停止放电',
        content: '确认要结束放电吗？',
        confirmText: '结束放电',
        cancelText: '取消',
        confirmColor: this.objColor2.textColor,
        success: (res) => {
          if (res.confirm) {
            // 停止放电
            this.clearTimeFun()
            this.stop();
          }
        }
      });
    },

    // 销毁定时器
    clearTimeFun() {
      if (times) {
        clearInterval(times)
      }
    }
  }
};
</script>

<style lang="less" scoped>
.powerCon {
  padding-top: 12rpx;
  background-color: #000000;
  min-height: 100vh;
  padding-bottom: 48rpx;
  font-family: PingFang SC;
  overflow-x: hidden;
}

.SVGACon {
  canvas {
    z-index: 1;
  }
}

.power-info-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  line-height: 60rpx;

  .text1 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 30rpx;
    color: #ffffff;
  }

  .text2 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: #ffffff;
  }

  .text3 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: #0fe485;

    display: flex;
    align-items: center;
  }

  .infoImg1 {
    width: 28rpx;
    height: 28rpx;
    margin-right: 10rpx;
  }

  .box1 {
    display: flex;
    justify-content: space-between;
    width: 700rpx;

    .box-item {
      width: 48%;
    }

    .box-item2 {
      display: flex;
      flex-direction: column;
      align-items: center;

      .text5 {
        font-family: DINPro-Medium, DINPro-Medium;
        font-weight: 400;
        font-size: 48rpx;
        color: #ffffff;
      }

      .text6 {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #ffffff;
      }
    }

    .text4 {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);

      text {
        font-size: 18rpx;
        color: #0fe485;
        margin-left: 10rpx;
      }
    }

    .infoImg {
      width: 18rpx;
      height: 18rpx;
      margin-left: 10rpx;
    }
  }
}

.stop-btn {
  width: 680rpx;
  height: 88rpx;
  background: linear-gradient(154deg, #fc724c 0%, #fc724c 0%, #f77e4a 100%);
  border-radius: 44rpx 44rpx 44rpx 44rpx;
  margin: 200rpx auto 0;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 30rpx;
  color: #ffffff;
  text-align: center;
  line-height: 88rpx;
}

.loading-warp {
  position: relative;
  height: 375rpx;

  .sosCon {
		font-size: 72rpx;
		font-weight: bold;
		color: #00FFAE;
		text-align: center;
		position: absolute;
		width: 100%;
		text-align: center;
		top: 148rpx;
		z-index: 9999;
		.sosScale {
			font-size: 30rpx;
		}
	}
}
</style>
